package com.examples.oryarok;


import static com.examples.oryarok.Constants.DATE;
import static com.examples.oryarok.Constants.FROM;
import static com.examples.oryarok.Constants.TABLE_NAME;
import static com.examples.oryarok.Constants.TAG;
import static com.examples.oryarok.Constants.TIME;


import android.app.ListActivity;
import android.content.Context;
import android.database.CharArrayBuffer;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.provider.MediaStore.Audio.Media;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.CursorAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;


public class MonthlyList extends ListActivity {
	
	private ListEntryAdapter mAdapter;
    //private NotifyingAsyncQueryHandler mQueryHandler;
	
	//my additions
	private static MeetDataDbHelper dbEntry;//dbEntry
	
	private Cursor getEntry(String daySt){
		SQLiteDatabase db = dbEntry.getReadableDatabase();
		String select = "(" + DATE + " LIKE '" + daySt + "')";
		Cursor cursor = db.query(TABLE_NAME, FROM, select, null, null, null, TIME + " DESC");
		startManagingCursor(cursor);
		return cursor;
	}
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "Monthly List Started");
        dbEntry = new MeetDataDbHelper(this);
        
        setContentView(R.layout.empty_list);
        
        mAdapter = new ListEntryAdapter(this, null);
        setListAdapter(mAdapter);
        Cursor cursor = getEntry("30.08.2011");//TODO just for test
        if (cursor != null) {
            startManagingCursor(cursor);
        }
        mAdapter.changeCursor(cursor);
        
        

        // Starts querying the media provider. This is done asynchronously not
        // to possibly block the UI or even worse fire an ANR...
        //mQueryHandler = new NotifyingAsyncQueryHandler(getContentResolver(), this);
        //mQueryHandler.startQuery(Media.EXTERNAL_CONTENT_URI, AudioFilesQuery.PROJECTION, AudioFilesQuery.SORT_ORDER);
    }
    
    public void onSetEmpty(View v) {
        mAdapter.changeCursor(null);
    }

    public void onSetData(View v) {
    	Cursor cursor = getEntry("23.08.2011");//TODO just for test
        mAdapter.changeCursor(cursor);
    }
	
	private static class ListEntryViewHolder {
        public TextView separator;
        public TextView nameView;//titleView;
        public CharArrayBuffer nameBuffer = new CharArrayBuffer(128);//titleBuffer
        public TextView phoneView;//subtitleView
        public StringBuilder phoneBuffer = new StringBuilder();//subtitleBuffer
    }
	
	
	private static class ListEntryAdapter extends CursorAdapter {

        /**
         * State of ListView item that has never been determined.
         */
        private static final int STATE_UNKNOWN = 0;

        /**
         * State of a ListView item that is sectioned. A sectioned item must
         * display the separator.
         */
        private static final int STATE_SECTIONED_CELL = 1;

        /**
         * State of a ListView item that is not sectioned and therefore does not
         * display the separator.
         */
        private static final int STATE_REGULAR_CELL = 2;

        private final CharArrayBuffer mBuffer = new CharArrayBuffer(128);
        private int[] mCellStates;

        public ListEntryAdapter(Context context, Cursor cursor) {
            super(context, cursor);
            mCellStates = cursor == null ? null : new int[cursor.getCount()];
        }

        @Override
        public void changeCursor(Cursor cursor) {
            super.changeCursor(cursor);
            mCellStates = cursor == null ? null : new int[cursor.getCount()];
        }

        @Override
        public void bindView(View view, Context context, Cursor cursor) {

            final ListEntryViewHolder holder = (ListEntryViewHolder) view.getTag();

            /*
             * Separator
             */
            boolean needSeparator = false;

            final int position = cursor.getPosition();
            cursor.copyStringToBuffer(3, holder.nameBuffer);//TODO use like AudioFilesQuery.TITLE for example for 3

            switch (mCellStates[position]) {
                case STATE_SECTIONED_CELL:
                    needSeparator = true;
                    break;

                case STATE_REGULAR_CELL:
                    needSeparator = false;
                    break;

                case STATE_UNKNOWN:
                default:
                    // A separator is needed if it's the first itemview of the
                    // ListView or if the group of the current cell is different
                    // from the previous itemview.
                    if (position == 0) {
                        needSeparator = true;
                    } else {
                    	//check if first character of the NAME different from previous
                        cursor.moveToPosition(position - 1);

                        cursor.copyStringToBuffer(3, mBuffer);//TODO use like AudioFilesQuery.TITLE for example for 3
                        if (mBuffer.sizeCopied > 0 && holder.nameBuffer.sizeCopied > 0 && mBuffer.data[0] != holder.nameBuffer.data[0]) {
                            needSeparator = true;
                        }

                        cursor.moveToPosition(position);
                    }

                    // Cache the result
                    mCellStates[position] = needSeparator ? STATE_SECTIONED_CELL : STATE_REGULAR_CELL;
                    break;
            }

            if (needSeparator) {
                holder.separator.setText(holder.nameBuffer.data, 0, 1);
                holder.separator.setVisibility(View.VISIBLE);
            } else {
                holder.separator.setVisibility(View.GONE);
            }

            /*
             * Title
             */
            holder.nameView.setText(holder.nameBuffer.data, 0, holder.nameBuffer.sizeCopied);

            /*
             * Subtitle
             */
            holder.phoneBuffer.setLength(0);
            final String phone = cursor.getString(5);//TODO use like AudioFilesQuery.ALBUM for example for 5
            if (!TextUtils.isEmpty(phone)) {
                holder.phoneBuffer.append(phone);
//                final String artist = cursor.getString(AudioFilesQuery.ARTIST);
//                if (!TextUtils.isEmpty(artist)) {
//                    holder.subtitleBuffer.append(" - ");
//                    holder.subtitleBuffer.append(artist);
//                }
            }
            
            if (TextUtils.isEmpty(holder.phoneBuffer)) {
                holder.phoneView.setVisibility(View.GONE);
            } else {
                holder.phoneView.setVisibility(View.VISIBLE);
                holder.phoneView.setText(holder.phoneBuffer);
            }
            
        }

        @Override
        public View newView(Context context, Cursor cursor, ViewGroup parent) {

            View v = LayoutInflater.from(context).inflate(R.layout.entry_list_item, parent, false);

            // The following code allows us to keep a reference on the child
            // views of the item. It prevents us from calling findViewById at
            // each getView/bindView and boosts the rendering code.
            ListEntryViewHolder holder = new ListEntryViewHolder();
            holder.separator = (TextView) v.findViewById(R.id.separator);
            holder.nameView = (TextView) v.findViewById(R.id.entry_list_name);
            holder.phoneView = (TextView) v.findViewById(R.id.entry_list_phone);

            v.setTag(holder);

            return v;
        }

    }


//	private ListAdapter listAd;
//		
//	//http://www.vogella.de/articles/AndroidListView/article.html#database
//	
//	static final String[] COUNTRIES = new String[] {
//	    "Afghanistan", "Albania", "Algeria", "American Samoa", "Andorra",
//	    "Angola", "Anguilla", "Antarctica", "Antigua and Barbuda", "Argentina",
//	    "Armenia", "Aruba", "Australia", "Austria", "Azerbaijan",
//	    "Bahrain", "Bangladesh", "Barbados", "Belarus", "Belgium"};
//	@Override
//	public void onCreate(Bundle savedInstanceState) {
//	  super.onCreate(savedInstanceState);
//	  listAd = new ArrayAdapter<String>(this, R.layout.list_dayly_item, R.id.line_txt, COUNTRIES);
//	  setListAdapter(listAd);
//
//	  ListView lv = getListView();
//	  lv.setTextFilterEnabled(true);
//
//	  lv.setOnItemClickListener(new OnItemClickListener() {
//	    public void onItemClick(AdapterView<?> parent, View view,
//	        int position, long id) {
//	      // When clicked, show a toast with the TextView text
//	      Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
//	          Toast.LENGTH_SHORT).show();
//	    }
//	  });
//	}
//	private class ItemAdapter extends BaseAdapter {
//		private String[] mData;
//		public ItemAdapter(String[] data) {
//			mData = data;
//		}
//		public int getCount() {
//			return mData.length;
//		}
//		public String getItem(int position) {
//			return mData[position];
//		}
//		public long getItemId(int position) {
//			return position;
//		}
//		public View getView(int position, View convertView, ViewGroup parent) {
//			if (convertView == null) {
//              convertView = getLayoutInflater().inflate(R.layout.text_item, parent, false);
//			}
//
//			((TextView) convertView).setText(getItem(position));
//
//          return convertView;
//      }
//			
//		
//		
//	}
	
	
	
	
	
	//	private Button butGo;
//	@Override
//	public void onCreate(Bundle savedInstanceState) {
//        super.onCreate(savedInstanceState);
//        setContentView(R.layout.list_monthly);
//        butGo = (Button)findViewById(R.id.button_weekly);
//        //butGo.setOnClickListener(this);
//        butGo.setOnClickListener(new OnClickListener() {
//            public void onClick(View view) {
//               Log.d("***DebugDen","Button Pressed");
//               butGo.setText("I am Pressed");
//               }
//        });
//    }

}
